//商家
(function() {
	var config = require("../_include/config");
	var db = require("../db/index");
	var md5 = require("../_include/md5");
	var helper = require("../_include/helper");
	var midEvent = require("../../middleware/index");
	var $Object = require("../_include/$.Object");
	var $Array = require("../_include/$.Array");
	var db_table_name = config.dbname.bus;
	//构造函数
	var _con = function(info, is_admin) {
		if (!info) {
			throwCusError("参数错误，商家信息不可为空");
		}
		var self = this;
		//类别标识
		self.type = "bus";
		//身份编号
		if (!info.name && (info.name = info.name.trim())) {
			throwCusError("商家名不可为空")
		}
		if (db.find_by_id(db_table_name, info.name)) {
			throwCusError("商家名已经存在");
		}
		//管理员模式不做限制
		if (info.name.length <= 5 && !is_admin) {
			throwCusError("商家名过短")
		}
		self._id = info.name; //(info&&info.name)||(info.name="B_"+Math.random().toString(16).substr(2)+(+new Date).toString(16));
		self.folder_name = info.folder_name || ("B_" + Math.random().toString(16).substr(2) + (+new Date).toString(16));
		//操作记录
		self._his = [];
		//额外信息
		self.info = {}; //info;

		// //地址
		// self.info.address = info.address||"";
		// //绑定的店铺名称
		// self.info.title = info.title||"";
		// //绑定的邮箱
		// self.info.email = info.email||"";
		// //绑定的手机
		// self.info.mobile_phone = info.phone||"";
		// //介绍
		// self.info.intro = info.intro||"";
		// //LOGO
		// self.logo_url = info.logo_url||"";
		// //合作物流
		// self.info.logistics = info.logistics||"";
		self.setInfo(info);

		//密码非明文存储
		self.info.password = md5.md5_2(info.password);

		//运费模板
		self.express_list = [];
		//员工
		self.employees = [];
		//仓库
		self.store = [];
		//订单历史
		self.ach = [];
		//评论
		self.comments = [];
		//收到的回复
		self.replys = [];
		//商家的标签
		self.tags = [];
		//商家的分类文件夹
		self.classifys = [];
		//所属联盟，目前的实现是一个商家只能加入一个联盟
		self.league = null; //[];
		//账号状态：未审核，审核中，审核通过、审核未通过、冻结（被举报并查出有问题）
		self.status = _con.STATE.审核通过;
		//所拥有的BUff
		self.buffs = [];
		//推荐商家是购买者所能获取到的BUFF福利，这个只能在商家中设置，个别商品无法独立设置，否则在计算的时候会出问题，届时改进算法
		self.recommend_buffs = [{
			max_price: 1000,
			rate: 0.2
		}];
		//用户积分返现配置，进阶式
		self.recommend_config = [ /*{max:num,per:per}*/ ];
		//推荐打折的额度
		self.recommend_discount = 0;
		self.recommend_config_buff_id = null; //要用的时候再进行初始化
		//导购链接返现配置，进阶式
		self.guide_config = [];
		self.guide_config_buff_id = null;
		self.guide_list = [];

		//商家的自定义配置信息
		self.config = {};

		//创建时间
		self.create_time = +new Date;
		//到期时间
		self.expiration_time = self.create_time + 30 * 24 * 60 * 60 * 1000;

		//但商家作为消费者登录时。对应的user_id
		self.user_id = null;

		//推荐商家进行注册父级商家
		var inviter_bus = info.pid && _con.get(info.pid);
		if (inviter_bus && inviter_bus.canInviteBus()) {
			console.log("推荐商家信息注册的商家是：", info.pid);
			self.pid = info.pid;
		}

		self.has_add_expiration_time = false;

		db.insert(db_table_name, self);
		console.log("注册了一个商家：", info.name);
	};

	module.exports = _con;

	//技能
	_con.prototype = require("./skill");

	_con.STATE = {
		"未审核": 0,
		"审核中": 1,
		"审核通过": 2,
		"审核未通过": 3,
		"冻结": 4
	};

	//不被JSON.stringify获取的属性
	_con.init_nojson_able_keys = function(obj) {
		var nojson_able_keys = [];
		Object.keys(obj).forEach(function(key) {
			if (obj[key] instanceof Array) {
				nojson_able_keys.push(key);
			}
		});
		//排除白名单对象
		var white_list = ["latest_goods_list", "perms"];
		white_list.forEach(function(key) {
			var _white_index = nojson_able_keys.indexOf(key);
			_white_index !== -1 && nojson_able_keys.splice(_white_index, 1);
		});
		//保存key
		if (obj.nojson_able_keys instanceof Array) {
			obj.nojson_able_keys = nojson_able_keys;
		} else {
			Object.defineProperty(obj, "nojson_able_keys", {
				enumerable: false,
				value: nojson_able_keys
			});
		}
		//固定黑名单
		if (!(obj.info.nojson_able_keys instanceof Array)) { //固定黑名单
			Object.defineProperty(obj.info, "nojson_able_keys", {
				enumerable: false,
				value: ["password"]
			});
		}
		return obj;
	};
	//静态方法
	_con.get = function(Id) {
		var result = db.find_by_id(db_table_name, Id);
		return _con.getInstance(result);
	};
	_con.getInstance = function(obj) {
		if (obj) {
			obj = _con.init_nojson_able_keys(obj);
			obj.__proto__ = _con.prototype;
			if (!obj.create_time) {
				obj.create_time = +new Date("2015-1-1");
				obj.expiration_time = +new Date("2015-6-1");
				obj.save();
			}
			if (obj._current_employee) {
				delete obj._current_employee;
			}
		}
		return obj;
	};
	_con.login = function(bus_info) {
		bus_info.name = bus_info.name.trim(); //.toLowerCase();
		if (bus_info.name.indexOf("@") !== -1) {
			//员工登录
			var name_info = bus_info.name.split("@");
			// var bus_id = name_info.shift();
			var bus_id = name_info.pop();
			var emp_name = name_info.join("@");
			var maybey_bus = db.find_by_id(db_table_name, bus_id);
			if (!maybey_bus) {
				throwCusError("员工登录账号有误，找不到指定商家");
			}
			maybey_bus = $Object.clone(maybey_bus);
			var bus = _con.getInstance(maybey_bus);
			var employees = bus.loginEmployees({
				name: emp_name,
				pwd: bus_info.password
			});
			console.log(bus_info.name, "员工登录成功");
			bus._current_employee = employees;
			return bus;
		} else {
			//管理员登录

			if (!bus_info.password) {
				throwCusError("登录密码不可为空")
			}
			bus_info.md5_pwd = md5.md5_2(bus_info.password)
			var maybey_bus = db.find_by_id(db_table_name, bus_info.name);
			if (!maybey_bus) {
				console.log("找不到编号为：“", bus_info.name, "”的商家！");
				maybey_bus = _con._loginByName(bus_info)
				if (!maybey_bus) {
					// maybey_bus = _con._loginByEmail(bus_info);
					if (!maybey_bus && bus_info.name.indexOf("@") !== -1) {
						maybey_bus = _con._loginByPhone(bus_info)
					}
					if (!maybey_bus && helper.phone(bus_info.name)) {
						maybey_bus = _con._loginByPhone(bus_info)
					}
				}
			}
			if (!maybey_bus) {
				throwCusError("找不到指定的商家");
			}
			// console.log(maybey_bus.info);
			if (maybey_bus.info.password !== bus_info.md5_pwd) {
				console.log("密码错误！", maybey_bus.info.password, bus_info.md5_pwd);
				throwCusError("密码错误");
			} else {
				console.log(bus_info.name, "登陆成功");
				return _con.getInstance(maybey_bus);
			}
		}
	};
	_con._loginByName = function(bus_info) {
		var maybey_bus = db.find_one(db_table_name, {
			info: {
				name: bus_info.name
			}
		});
		// if (maybey_bus && maybey_bus.info.password === bus_info.md5_pwd) {
		// 	return maybey_bus
		// }
		if (!maybey_bus) {
			console.log("找不到名字为：“", bus_info.name, "”的商家！");
		}
		return maybey_bus
	}
	_con._loginByEmail = function(bus_info) {
		var maybey_bus = db.find_one(db_table_name, {
			info: {
				email: bus_info.name
			}
		});
		// if (maybey_bus && maybey_bus.info.password === bus_info.md5_pwd) {
		// 	return maybey_bus
		// }
		if (!maybey_bus) {
			console.log("找不到邮箱为：“", bus_info.name, "”的商家！");
		}
		return maybey_bus
	}
	_con._loginByPhone = function(bus_info) {
		var maybey_bus = db.find_one(db_table_name, {
			info: {
				mobile_phone: bus_info.name
			}
		});
		// if (maybey_bus && maybey_bus.info.password === bus_info.md5_pwd) {
		// 	return maybey_bus
		// }
		if (!maybey_bus) {
			console.log("找不到电话号码为：“", bus_info.name, "”的商家！");
		}
		return maybey_bus
	}
}());